package com.apes.fn.scm.saleReport.service.process.orderProcess;

import com.apes.fn.crm.customerExpand.FnCustomerExpand;
import com.apes.fn.scm.retailOrder.model.RetailOrder;
import com.apes.fn.scm.retailOrder.model.RetailOrderExtension;
import com.apes.fn.scm.retailOrder.model.RetailOrderItem;
import com.apes.fn.scm.retailOrder.repository.RetailOrderExtensionRepository;
import com.apes.fn.scm.retailOrder.repository.RetailOrderRepository;
import com.apes.fn.scm.retailReturn.RetailReturnItem;
import com.apes.fn.scm.retailReturn.RetailReturnItemRepository;
import com.apes.fn.scm.saleReport.service.process.CreateDetailsProcess;
import com.apes.fn.server.productReceive.ProductReceiveItem;
import com.apes.fn.server.productReceive.ProductReceiveItemRepository;
import com.apes.fn.server.servicePlan.model.ServicePlanItem;
import com.apes.fn.server.servicePlan.repository.ServicePlanItemRepository;
import com.apes.fn.server.workOrder.model.MaintenanceOrder;
import com.apes.fn.server.workOrder.repository.MaintenanceOrderRepository;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.Arith;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.car.model.CarConfiguration;
import com.apes.scm.masterdata.car.model.CarLabel;
import com.apes.scm.masterdata.car.model.CarModel;
import com.apes.scm.masterdata.car.repository.CarConfigurationRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.product.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 零售单生成营业额明细
 */
@Service
public class RetailOrderProcess extends CreateDetailsProcess {
    @Autowired
    private RetailOrderRepository retailOrderRepository;
    @Autowired
    private CarConfigurationRepository carConfigurationRepository;
    @Autowired
    private RetailOrderExtensionRepository retailOrderExtensionRepository;
    @Autowired
    private ServicePlanItemRepository servicePlanItemRepository;
    @Autowired
    private RetailReturnItemRepository retailReturnItemRepository;
    @Autowired
    private MaintenanceOrderRepository maintenanceOrderRepository;
    @Autowired
    private ProductReceiveItemRepository productReceiveItemRepository;

    @Override
    public void process(SimpleRequest request) {
        String id = request.get("id");
        RetailOrder retailOrder = retailOrderRepository.findOne(id);
        int count = 0;
        double amt = 0;
        double saleCommission = 0;
        for (RetailOrderItem retailOrderItem : retailOrder.getSaleItems()) {
            double packageCommission = retailOrder.getPackageCommission();
            if(packageCommission != 0){
                count++;
                int size = retailOrder.getSaleItems().size();
                if(count == size){
                    saleCommission = packageCommission - amt;
                } else {
                    saleCommission = Arith.round(packageCommission / size,2);
                    amt += saleCommission;
                }
            }
            createDetails(MapUtil.mapper("order", retailOrderItem,"saleCommission",saleCommission));
        }
    }

    /**
     * @param map {"order": RetailOrderItem}
     *
     */
    @Override
    public Map<String, Object> getModel(Map map) {
        RetailOrderItem retailOrderItem = (RetailOrderItem) map.get("order");
        RetailOrder retailOrder = retailOrderItem.getOrder();
        Product product = retailOrderItem.getProduct();
        //零售单扩展表
        RetailOrderExtension retailOrderExtension = retailOrderExtensionRepository.findByRetailOrderItemId(retailOrderItem.getId());
        //车辆扩展信息
        FnCustomerExpand fnCustomerExpand = retailOrder.getCustomerExpand();
        //厂牌
        CarLabel carLabel = null;
        //车型
        CarModel carModel = null;
        //车牌
        String carLicense;
        if(fnCustomerExpand != null){
            carLicense = fnCustomerExpand.getCarLicense();
            String jekunModelCode = fnCustomerExpand.getJekunModelCode();
            if(jekunModelCode != null) {
                //配置车型
                CarConfiguration carConfiguration = carConfigurationRepository.findOne(jekunModelCode);
                if(carConfiguration != null){
                    carLabel = carConfiguration.getCarLabel();
                    carModel = carConfiguration.getCarModel();
                }
            }
        } else {
            carLicense = retailOrderExtension.getCarLicense();
        }

        ServicePlanItem servicePlanItem;
        MaintenanceOrder maintenanceOrder = null;
        PartyRole receiver = null;
        String worker = "";
        //通过来源单据明细号找方案明细
        if(retailOrderItem.getOriginnumber() != null){
             servicePlanItem = servicePlanItemRepository.findOne(retailOrderItem.getOriginnumber());
            if(servicePlanItem == null){
                //零售退货要先找零售原单
                RetailReturnItem retailReturnItem = retailReturnItemRepository.findOne(retailOrderItem.getOriginnumber());
                if(retailReturnItem != null && retailReturnItem.getRetailOrderItem() != null) servicePlanItem = servicePlanItemRepository.findOne(retailReturnItem.getRetailOrderItem().getOriginnumber());
            }
            if(servicePlanItem != null){
                //如果方案明细有关联工单号
                if (servicePlanItem.getRelevanceWorkOrder() != null) {
                    maintenanceOrder = maintenanceOrderRepository.findOne(servicePlanItem.getRelevanceWorkOrder());
                } else {
                    //没有关联工单号就通过方案明细id找工单
                    maintenanceOrder = maintenanceOrderRepository.findByServicePlanItemAndBusinessType(servicePlanItem,"common");
                }
                //根据方案明细找到最后一张领用单获取到领用人
                ProductReceiveItem productReceiveItem = productReceiveItemRepository.findMaxByServicePlanItemId(servicePlanItem.getId());
                if(productReceiveItem != null) receiver = productReceiveItem.getProductReceive().getReceiver();
            }
        }
        if(maintenanceOrder != null) worker = maintenanceOrder.getWorker1() + "|" +maintenanceOrder.getWorker2() + "|" + maintenanceOrder.getWorker3() + "|" + maintenanceOrder.getWorker4();
        return MapUtil.mapper("carLicense",carLicense,"product",product,
                "productUom",product.getUom(),"qty",retailOrderItem.getProductUomQty(),"salesAmount",retailOrderItem.getPriceTotal(),
                "serveType",product.getServeType(),"dept",retailOrder.getDept(),"company",retailOrder.getCompany(),
                "origin",retailOrder.getId(),"originItem",retailOrderItem.getId(),"originBusinessType","retailOrder",
                "originCreateDate",retailOrder.getDateApprove(),"source", retailOrder.getOrigin(),"sourceBusinessType",retailOrder.getOrderType(),
                "productGroup",product.getProductGroup(),"classify",product.getClassify(),"saleCommission",map.get("saleCommission"),
                "brand",product.getBrand(),"tax",retailOrderItem.getTax(),"carLabel",carLabel,"carModel",carModel,
                "pftPriceUnit",retailOrderItem.getPftPriceUnit(),"priceUnit",retailOrderItem.getPriceUnit(),"receiver",receiver,
                "discountAmount",retailOrderItem.getDiscountAmount(),"couponDiscountAmount",retailOrderExtension.getCouponDiscountAmount(),
                "mainSalesman",retailOrderItem.getMainSalesman(),"subSalesman",retailOrderItem.getSubSalesman(),"worker",worker,
                "baobeiEnvelopeCash",retailOrderExtension.getBaobeiEnvelopeCash(),"redEnvelopeCash",retailOrderExtension.getRedEnvelopeCash(),
                "cardDiscount",retailOrderExtension.getTicketDiscountAmount(),"heterodoxyDiscount",retailOrderExtension.getCrossDiscountAmount(),
                "cashierDeskDiscountAmount",retailOrderExtension.getCashierDeskDiscountAmount());
    }

    @Override
    public boolean support(String type) {
        return "retailOrder".equals(type);
    }

}
